<template>
	<view>
		<view class='fjs' @tap="format">
			<view :class="{'ql-active': formats.bold}" class="iconfont icon-zitijiacu" data-name="bold"></view>
			<view :class="{'ql-active' : formats.italic}" class="iconfont icon-zitixieti" data-name="italic"></view>
			<view :class="{'ql-active' : formats.underline}" class="iconfont icon-zitixiahuaxian" data-name="underline"></view>
			<view :class="{'ql-active' : formats.fontSize === '24px'}" class="iconfont icon-fontsize" data-name="fontSize" data-value="24px"></view>
			<view :class="{'ql-active' : formats.color === '#0000ff'}" class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
			<view class="iconfont icon-charutupian" @tap="insertImage"></view>
			<view class="iconfont icon-shanchu" @tap="clear"></view>
		</view>
		
		<editor id="editor" class="ql-container" :placeholder="placeholder" :show-img-size="true" :show-img-toolbar="true" :show-img-resize="true" @statuschange="statusChange" @ready="editorReady" @input="input">
		 {{value}}
		</editor>
	</view>
</template>

<script>
import api from '@/config/api'
import app from '@/config/app'
import Emitter from 'uview-plus/libs/util/emitter'

export default {
	mixins: [Emitter],
	props: {
		value: {
			type: String,
			default: ''
		},
		placeholder: {
			type: String,
			default: '请输入'
		},
		tools: {
			type: Array,
			default: () => ['bold', '']
		},
		width: {
			type: [String, Number],
			default: 160
		},
		height: {
			type: [String, Number],
			default: 160
		}
	},
	data() {
		return {
			formats: {},
			ctx: null
		}
	},
	methods: {
		editorReady() {
			this.$nextTick(()=>{
				uni.createSelectorQuery().in(this).select('#editor').context(res => {
					this.ctx = res.context
					this.ctx.setContents({html:this.value})
					uni.pageScrollTo({
						scrollTop: 0,
						selector: 'page',
						duration: 300
					})
				}).exec()
			})
		},
		undo() {
			this.ctx.undo()
		},
		redo() {
			this.ctx.redo()
		},
		format(e) {
			const { name, value } = e.target.dataset
			name && this.ctx.format(name, value)
		},
		statusChange(e) {
			this.formats = e.detail
		},
		input(e){
			this.$emit('update:value', e.detail.html)
			setTimeout(() => {
				// 将当前的值发送到 u-form-item 进行校验
				this.dispatch('u-form-item', 'onFieldChange', e.detail.html)
			}, 40)
		},
		insertDivider() {
			this.ctx.insertDivider({
				success () {
				}
			})
		},
		clear() {
			this.ctx.clear({
				success (res) {
					this.$emit('update:value', '')
				}
			})
		},
		removeFormat() {
			this.ctx.removeFormat()
		},
		insertDate() {
			const date = new Date()
			const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
			this.ctx.insertText({
				text: formatDate
			})
		},
		insertImage() {
			const that = this
			uni.chooseImage({
				sizeType: ['compressed'],
				count: 9,
				success (chooseImageRes) {
					const list = {}
					let index = 0
					const tempFilePaths = chooseImageRes.tempFilePaths
					const l = tempFilePaths.length
					tempFilePaths.map((tempFile, i)=>{
						// #ifndef H5
						uni.compressImage({
							src: tempFile,
							width: '320px',
							height: 'auto',
							quality: 50,
							success ({tempFilePath}) {
						// #endif
						// #ifdef H5
						const tempFilePath = tempFile
						// #endif
						uni.uploadFile({
							url: api.upload, //仅为示例，非真实的接口地址
							filePath: tempFilePath,
							name: 'file',
							formData: {},
							success (res) {
								if(res.statusCode === 200){
									list[i] = res.data
									index += 1
									if(index == l){
										for(const n in list){
											that.ctx.insertImage({
												src: app.imgRoot + list[n],
												alt: '图像'
											})
										}
									}
								}
							}
						})
						// #ifndef H5
							}
						})
						// #endif
					})
				}
			})
		}
	},
	create() {
		uni.loadFontFace({
			family: 'Pacifico',
			source: 'url("https://sungd.github.io/Pacifico.ttf")'
		})
	},
	watch: {
		value(newVal, oldVal){
			if(this.ctx){
				this.ctx.setContents({html:newVal})
			}
		}
	}
}
</script>

<style scoped>
	@import "./icon.css";
	.iconfont {
		padding: 4rpx 4rpx;
		cursor: pointer;
		font-size: 20px;
	}
	.toolbar {
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}
	.ql-container {
		box-sizing: border-box;
		width: 720rpx;
		min-height: 200rpx;
		height: auto;
		background: #fff;
		margin-top: 20rpx;
		font-size: 30rpx;
		line-height: 1.5;
	}
	.ql-active {
		color: #06c;
	}
</style>
